package com.ase.mobile.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ase.mobile.entity.User;
import com.ase.mobile.entity.UserExample;
import com.ase.mobile.enums.NbaEnum;
import com.ase.mobile.mapper.UserMapper;
import com.ase.mobile.service.NbaPlayerService;
import com.ase.mobile.utils.RedisUtils;
import com.ase.mobile.utils.result.ResUtils;
import com.ase.mobile.utils.result.Result;
import com.ase.mobile.utils.result.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;


/**
 * @author Curry
 */
@Service
public class NbaPlayerServiceImpl implements NbaPlayerService {
    private static Logger log = LoggerFactory.getLogger(NbaPlayerServiceImpl.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result listNbaPlayer() {
        //step1 先从redis中取
        String nbaPlayerListCache = (String) redisUtils.hmGet(NbaEnum.NBA_PLAYER_CACHE.getName(), NbaEnum.NBA_PLAYER_CACHE.getName());
        //如果redis缓存中nbaPlayerCache没有数据
        if (StringUtils.isEmpty(nbaPlayerListCache)) {
            HashMap<String, Object> map = new HashMap<>();
            log.info("正在从MySQL数据库中取值......");
            // step2 如果拿不到则从DB取值
            UserExample userExample = new UserExample();
            List<User> userList = userMapper.selectByExample(userExample);
            String userJsonString = JSONArray.toJSONString(userList);
            map.put(NbaEnum.NBA_PLAYER_CACHE.getName(), userJsonString);
            // step3 MySQL数据库非空情况刷新redis值
            if (!userList.isEmpty()) {
                redisUtils.hmSet(NbaEnum.NBA_PLAYER_CACHE.getName(), NbaEnum.NBA_PLAYER_CACHE.getName(), map.get(NbaEnum.NBA_PLAYER_CACHE.getName()));
                log.info("MySQL数据库中相关数据已经同步到redis数据库中");
                return ResUtils.success(map.get(NbaEnum.NBA_PLAYER_CACHE.getName()));
            }
            log.info("MySQL数据库中没有相关数据");
            return ResUtils.success(Status.DATA_MySQL_IS_NULL);
        }
        log.info("从redis数据库缓存取值");
        return ResUtils.success(JSONObject.parseArray(nbaPlayerListCache, User.class));
    }
}
